package geektime.spring.springbucks.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import geektime.spring.springbucks.entity.Coffee;
import geektime.spring.springbucks.exception.RollbackException;
import geektime.spring.springbucks.mapper.CoffeeMapper;
import geektime.spring.springbucks.service.CoffeeService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;


@Service("coffeeService")
@Transactional(rollbackFor = {RollbackException.class})
public class CoffeeServiceImpl extends ServiceImpl<CoffeeMapper, Coffee> implements CoffeeService {

    @Override
    public List<Coffee> listByPage(Long pageNum, Long pageSize) {
        return baseMapper.listByPage(pageNum, pageSize);
    }


    @Override
    public boolean create(Coffee coffee) throws RollbackException {
        boolean result = save(coffee);

        if (coffee.getName() == "rollback") {
            throw new RollbackException("咖啡的名称是：'rollback'，所以回滚了！");
        }

        return result;
    }


    @Override
    public int update(Coffee coffee) throws RollbackException {
        int result = baseMapper.updateById(coffee);

        if (coffee.getName() == "rollback") {
            throw new RollbackException("咖啡的名称是：'rollback'，所以回滚了！");
        }

        return result;
    }


    @Override
    public int delete(Long id) throws RollbackException {
        int result = baseMapper.deleteById(id);

        List list = new ArrayList<Long>();
        list.add(1L);
        list.add(2L);
        list.add(3L);
        list.add(4L);
        list.add(5L);

        if (list.contains(id)) {
            throw new RollbackException("删除的记录ID在[1,2,3,4,5]中，所以回滚了！");
        }

        return result;
    }


    @Override
    public void interceptFilter(String sql) {
        baseMapper.interceptFilter(sql);
    }


}